<?php
/**
 *Important properties
 *
 *fieldSeparator - character used to divide fields in CSV file (default: ; );
 *quote - character used to quote text fields in CSV file (default: " );
 */
class ArrowTableExport extends ArrowTagContainer{

	public function configure(){
		$this->addProperties(array(
			"export"=>0, 
			"import" => false, 
			"validate" => false, 
			"filename"=>"data.csv", 
			"fields" => "", 
			'additionalFields'=>'', 
			"fieldSeparator"=>";", 
			"quote"=>'"', 
			"title"=>'',
			"validationDelegate" => null,
			"informationDelegate" => null,
			"importDelegate" => null 
		));
		//$this->addRequiredProperties(array("fields", "title"));
		$this->setRequiredParent("ArrowTable");
		$this->setDisplay(false);
		$this->addStateProperties(array("export", "import", "validate"));
	}

	public function generateBlockStart(){
		if ($this->getState('export')){
			$this->generateExport();
		}
		if ($this->getState('import')){
			print $this->processImport();
		}

		if ($this->getState('validate')){
			print $this->processValidation();
		}
	}

	public function generateBlockEnd(){
		$code = "";
		if(!$this->getState('import') && !$this->getState('validate')){
			$title = $this->getProperty('title');
			$code = '<a class="ctrl-table-csv" target="_blank" href="'.$this->getStateChangeLink(array('export'=>'1'),true).'">'.$title.'</a>';
			$code.= '<a class="ctrl-table-csv"  href="#" onclick="$(this).next().toggle();">&nbsp;</a>';
			$code.= '<div style="display: none;">';
			$code.= '<form target="upload_iframe" action="'.$this->getStateChangeLink(array('validate'=>'1'),true).'" method="post" enctype="multipart/form-data">';
			$code.= '<input type="file" name="importFile" style="padding: 5px;" /><input type="submit" value="Ładuj" style="padding: 5px;" /></form>';
			$code.= '<iframe id="upload_iframe" name="upload_iframe" style="width: 400px; height: 100px; display: none;" onload="alert(\'zaladowalem\'">
				 </iframe></div>';
		}
		return $code;
	}

	public function processValidation(){
		print_r($_FILES);
		$code = '<script type="text/javascript">';
		
		if(empty($_FILES["importFile"]["tmp_name"])){
			$code.= 'window.parent.alert("Nie wskazano pliku");';
		}else if(strpos($_FILES["importFile"]["name"] , ".csv") == false){
			$code.= 'window.parent.alert("Akceptowane są tylko pliki w formacie CSV");';

		}else{
			
			$contents = self::parseCSVFile($_FILES["importFile"]["tmp_name"], $this->getProperty("fieldSeparator"), $this->getProperty("quote"));
			
			$validateFormat = $this->validateFileFormat($contents);
			
			if( $this->getProperty("validateDelegate") != null  )
				$resultValidateDelegate = call_user_func(array(ArrowView::getCurrentView(), $this->getProperty("validateDelegate")), $contents);

			if( $validateFormat["pass"] == false)
				$code.= 'window.parent.alert("Format pliku nie poprawny: '.$validateFormat["message"].'");';
		
			else if( isset($resultValidateDelegate) && $resultValidateDelegate["pass"] == false ){
				$code.= 'window.parent.alert("Format pliku nie poprawny: '.$resultValidateDelegate["message"].'");';
				
			}else{	
				copy( $_FILES["importFile"]["tmp_name"], ARROW_CACHE_PATH."/tmp_import_file.csv");
				
				if( $this->getProperty("informationDelegate") != null  ){
					//print_r($this->getTemplateHost());
					//exit();
					
					$resultInformationDelegate = call_user_func(array($this->getTemplateHost(), $this->getProperty("informationDelegate")), $contents);
					$code.= 'if(window.parent.confirm("'.$resultInformationDelegate.'\nKontynuować?")) window.location.href = "'.$this->getStateChangeLink(array('import'=>'1', 'validate' => 0),true).'";';
				}else{
					$code.= 'window.location.href = "'.$this->getStateChangeLink(array('import'=>'1', 'validate' => 0),true).'";';
				}
			}
			
		}
		$code.= '</script>';

		print $code;
	}

	private function validateFileFormat($file){
		//$contents = file_get_contents($file);


		return( array("pass" => true, "message" => ""));
		
	}

	public function processImport(){
		$contents = self::parseCSVFile(ARROW_CACHE_PATH."/tmp_import_file.csv", $this->getProperty("fieldSeparator"), $this->getProperty("quote"));
		$resultImportDelegate = call_user_func(array($this->getTemplateHost(), $this->getProperty("importDelegate")), $contents);
		$code = '<textarea style="width: 100%; height:400px;">'.print_r($contents, 1)."</textarea>";
		$code.= '<script type="text/javascript">window.parent.alert("Wykonane.\n'.$resultImportDelegate.'");</script>';
		print $code;
	}


	public function generateExport(){
		$parent = $this->getParent('ArrowTable');
		$parent->prepareList();
		$crit = clone $parent->getCriteria();
		$model = $parent->getProperty('model');
		$class = explode('.',$model);
		$class = end($class);
			
		//Set special conditions
			
			
		//Set columns to download
		$fields = $this->getProperty('fields');
		if (!empty($fields)){
			$crit->setEmptyList();
			$fields = explode(';',$fields);
			foreach($fields as $field);
			$crit->addColumn($field);
		}
		else{
			$fields = $this->getProperty('additionalFields');
			if (!empty($fields)){
				$fields = explode(';',$fields);
				foreach($fields as $field);
				$crit->addColumn($field);
			}
		}
		$crit->clearLimit();

		$data = call_user_func(array($class,'getRawData'),$crit,$class);
		$quote = $this->getProperty('quote');
		$separator = $this->getProperty('fieldSeparator');
		$line_separator = "\r\n";
		$content = '';
		foreach ($data as $row){
			//TODO : trzeba zamieniďż˝ $separator na $separator$separator (" => "") aby byďż˝o zgodne ze standardem
			$content .= $quote.implode($quote.$separator.$quote,$row).$quote.$line_separator;
		}
		$filename = $this->getProperty('filename');
		if(isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'],'MSIE'))
		header('Content-Type: application/force-download');
		else
		header('Content-Type: application/octet-stream');
			
		if(headers_sent()){
			throw new ArrowException('Some data has already been output to browser, can\'t send  file');
		}
		header('Content-Length: '.strlen($content));
		header('Content-disposition: attachment; filename="'.$filename.'"');
		echo $content;
		ArrowController::end();
	}
	
	
	private static function parseCSVFile($file, $separator){
		$arr = file($file);
		$tmp = array();
		
		foreach($arr as $row){
			if( !empty($row) )
				$tmp[] = self::str_getcsv($row, $separator);	
		}
		
		return $tmp;
	}
	
	private static  function str_getcsv($input, $delimiter=';', $enclosure='"', $escape=null, $eol=null) { 
	  $temp=fopen("php://memory", "rw"); 
	  fwrite($temp, $input); 
	  fseek($temp, 0); 
	  $r = array(); 
	  while (($data = fgetcsv($temp, 4096, $delimiter, $enclosure)) !== false) { 
	    $r[] = $data; 
	  } 
	  fclose($temp); 
	  return $r[0]; 
	} 	
	
	
}
?>
